<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>搞清楚this</title>
</head>
<body>
<button onclick="btnClick()">once</button>
<script>
    // 使用call实现bind
    Function.prototype.mybind = function(context) {
        let self = this;  // 这里的this指向的是函数体
        console.log(self);
        return function () {
            self.apply(context,arguments)
        }
    }
    function test() {
        console.log(this.name);
    }
    let obj = {name: "Samuel"};
    let res = test.mybind(obj);
    res();


    //  滴滴面试
    function A() {
        this.name = 'Samuel'
    }
    A.prototype.foo = function () {
        console.log(this);
    }
    var a = new A();
    var b = {name:"b"};
    var c = {name:"c"};
    var foo2 = a.foo.bind(b);
    foo2();
    var foo3 = foo2.bind(c)
    foo3();

    // 绑定丢失
    function foo() {
        console.log(arguments)
        console.log(this.aaa);
    }
    var obj1 = {
        aaa : 'obj aaa',
        foo : foo
    };
    var aaa = 'global aaa';
    function doFoo(fn) {
        fn()
    }
    doFoo(obj1.foo); // -> global aaa

    // 思考题
    var num = 1;
    var myObject = {
        num: 2,
        add: function() {
            this.num = 3;
            (function() {   // 自调用函数是默认绑定规则，this指向window
                console.log(this.num);
                this.num = 4;
            })();
            console.log(this.num);
        },
        sub: function() {
            console.log(this.num)
        }
    }
    myObject.add();
    console.log(myObject.num);
    console.log(num);
    var sub = myObject.sub;  // 引用传递，绑定丢失，this指向window
    sub();

    function test() {
        console.log(this.a)
    }
    var a = 123
    var obj = {
        a: 234
    }
    test.call(obj)
</script>
</body>
</html>
